package io.e2x.testground.fruitstore.service.impl;

import io.e2x.testground.fruitstore.dal.entities.User;
import io.e2x.testground.fruitstore.repo.UserRepo;
import io.e2x.testground.fruitstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.math.BigInteger;

@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepo userRepo;


    @Override
    public Mono<User> getUser(long id) {
        return userRepo.findById(id);
    }

    @Override
    public Mono<Void> addUser(User user) throws  RuntimeException {
        return ifPhoneNotExist(user.getPhone())
                .then(userRepo.save( user)).then();
    }

    @Override
    public Mono<User> getUserByUserName(String username) {
        return userRepo.findUserByUsername(username);
    }

    private Mono<Void> ifPhoneNotExist(String phone) {
        return userRepo.findByPhone(phone)
                .hasElement()
                .flatMap(exists -> {
                    if (exists) {
                        return Mono.error(new RuntimeException("手机号已存在"));
                    } else {
                        return Mono.empty();
                    }
                });
    }
}
